import { computed, onMounted, reactive, ref } from "vue";
import { LoginLog } from "@/api/model/logModel";
import { getOnlineList, kickout } from "@/api/online";
import { OnlineInfo } from "@/api/model/onlineModel";
import { message } from "@/utils/message";

export function useOperator() {
  const form: LoginLog = reactive({
    size: 10,
    current: 1,
  });
  const btnDisable = ref(false);
  const btnName = ref("加载更多");
  const dataList = ref<OnlineInfo[]>([]);
  const loading = ref(true);
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列"),
    },
    {
      label: "登录ID",
      prop: "loginId",
    },
    {
      label: "登录用户",
      prop: "username",
    },
    {
      label: "登录设备",
      prop: "device",
    },
    {
      label: "用户昵称",
      prop: "nickname",
    },
    {
      label: "登录时间",
      prop: "loginDate",
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
    },
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary",
    ];
  });

  function load() {
    loading.value = true;
    getOnlineList(form)
      .then(res => {
        if (res.length > 0) {
          dataList.value.push(...res);
          form.current += 1;
        } else {
          btnDisable.value = true;
          btnName.value = "没有更多了";
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function reload() {
    dataList.value = [];
    form.current = 1;
    btnDisable.value = false;
    btnName.value = "加载更多";
    load();
  }

  function kickoutUser(row) {
    kickout(row.token)
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      })
      .finally(() => {
        reload();
      });
  }

  onMounted(() => {
    load();
  });

  return {
    loading,
    columns,
    dataList,
    buttonClass,
    reload,
    load,
    btnDisable,
    btnName,
    kickoutUser,
  };
}
